package com.javatech.controller;

import com.javatech.entity.AnythingReq;
import com.javatech.entity.AnythingRsp;
import com.javatech.entity.ChatReq;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Flux;

import java.time.Duration;

/**
 * the LocalKnowledgeController
 *
 * @author java-tech
 * @date 2025-03-03
 */
@Slf4j
@RestController
@RequestMapping("api")
public class LocalKnowledgeController {

    @Autowired
    private WebClient webClient;

    @PostMapping(value = "chat")
    public ResponseEntity<String> chat(@RequestBody ChatReq chatReq) {
        log.info("---> chat req={}", chatReq);
        String message = chatReq.getMessage();

        String resp = webClient.post()
                .uri("/v1/workspace/test/chat")
                .contentType(MediaType.APPLICATION_JSON)
                .bodyValue(new AnythingReq(message, "chat"))
                .retrieve()
                .bodyToMono(AnythingRsp.class)
                .map(r -> r != null && r.getTextResponse() != null ? r.getTextResponse() : "")
                .filter(StringUtils::hasLength)
                .block(Duration.ofSeconds(60));
        log.info(">>>>>rsp={}", resp);
        return ResponseEntity.ok(resp);
    }


    @PostMapping(value = "streamchat")
    public ResponseEntity<Flux<String>> streamchat(@RequestBody ChatReq chatReq) {
        log.info("---> streamchat req={}", chatReq);
        String message = chatReq.getMessage();

        Flux<String> resp = webClient
                .post()
                .uri("/v1/workspace/test/stream-chat")
                .contentType(MediaType.APPLICATION_JSON)
                .bodyValue(new AnythingReq(message, "chat"))
                .retrieve()
                .bodyToFlux(AnythingRsp.class)
                .map(r -> r != null && r.getTextResponse() != null ? r.getTextResponse() : "")
                .filter(StringUtils::hasLength)
                .doOnNext(System.out::println);
        log.info(">>>>>rsp2={}", resp);
        return ResponseEntity.ok(resp);
    }

}
